package com.bwhk.splitdata.split;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import com.bwhk.splitdata.mailss;
import com.bwhk.splitdata.utils.JsonUtil;

@Component  
@RabbitListener(queues = "split_work")
@Scope("prototype")
public class MessageReceiver {
	
	protected static Logger logger=LoggerFactory.getLogger(MessageReceiver.class);
	
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    mailss m;
	
	private String name;
    
    public MessageReceiver() {
    	this.name="";
    }
    
    public MessageReceiver(String name) {
    	this.name=name;
    }
    
	@RabbitHandler  
    public void process(String json) throws UnsupportedEncodingException, IllegalArgumentException {  
		
        logger.info("HelloReceiver : " + json);
        
        MessageObject mo = (MessageObject) JsonUtil.toObject(json, MessageObject.class);
  
        logger.info("======================="+mo.getWatch_item_id());
        logger.info("======================="+mo.getValueType());
        String ValueSql = "";
        
        
    	if("1".equals(mo.getStatus())){
    		if("1".equals(mo.getValueType())){
                logger.info("==========jinle=============");
            	ValueSql = "select hi.value from history_str hi,(select itemid, max(clock) c from history_str group by itemid) hi2 where hi.itemid=hi2.itemid and hi.clock=hi2.c and hi.itemid = "+mo.getWatch_item_id();
            }else{
            	ValueSql = "select hi.value from history hi,(select itemid, max(clock) c from history group by itemid) hi2 where hi.itemid=hi2.itemid and hi.clock=hi2.c and hi.itemid = "+mo.getWatch_item_id();
            }

            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
            Object moValue;
            String leftValue="";
            boolean isOk = true;
            try{
            	logger.info("=============录入data表================"+this.queryMySql(ValueSql));
            	moValue = this.queryMySql(ValueSql);
            	if(moValue != null){
            		leftValue = String.valueOf(moValue);
            	}
            	Object[] param = new Object[] {mo.getId(),leftValue,"N",sdf2.format(new Date()),new Date(),mo.getWatch_item_id()};
    	    	jdbcTemplate.update("insert into iyw_watch_item_data(item_id,value,is_error,run_period_day,run_date,watch_item_id) values(?,?,?,?,?,?)",   
    	    			param);
            } catch (DataAccessException e) {
            	logger.info("=============录入data表为空的================");
    			logger.warn("warn:SQL取值为空！");
    			leftValue = "";
            	Object[] param = new Object[] {mo.getId(),leftValue,"Y","取值为空！",sdf2.format(new Date()),new Date(),mo.getWatch_item_id()};
    	    	jdbcTemplate.update("insert into iyw_watch_item_data(item_id,value,is_error,error_msg,run_period_day,run_date,watch_item_id) values(?,?,?,?,?,?,?)",   
    	    			param);
    	    	isOk = false;
    		}
            //如果没有错误执行触发器
            if(isOk == true){
            	//获取id,msg
    	    	try {
    	    		//获取触发器信息
    	    		List ls = this.queryForItemTrigger(mo.getId());
    	        	if(ls != null){
    	        		//循环读取触发器
    	        		for(int i = 0;i<ls.size();i++){
    	    		    	Map map = (Map)ls.get(i);
    	    		    	Long id = (Long)map.get("id");
    	    		    	String isconntinue = (String)map.get("is_conntinue");
    	    		    	String name = (String)map.get("trigger_name");
    	    		    	String msg = (String)map.get("tigger_message");
        					String type = (String)map.get("trigger_type");
        					String shell = (String)map.get("shell");
        					String level = (String)map.get("warning_level");
    						logger.info("trigger_type========="+type);
    						if("N".equals(isconntinue)){
    		    		    	//获取触发器条目信息
    		    		    	List ls2 = this.queryForItemTriggerLine(id);
    		    		    	int j = 0;
    		    		    	if(ls2 != null){
    		    		    		//循环比对条目
    		    		    		for(int k = 0;k<ls2.size();k++){
    		    		    			//获取符号与对比值
    		    		    	    	Map map2 = (Map)ls2.get(k);
    		    		    	    	String oper = (String)map2.get("oper");
    		    		    	    	String value = (String)map2.get("value");
    		    		    	    	if("==".equals(oper)){
    		    		    	    		oper = "=";
    		    		    	    	}
    		    		    	    	//条目比对是否满足，返回true false
    		    		    	    	String sql = "select if("+"'"+leftValue+"'"+oper+"'"+value+"'"+",\"true\",\"false\")";
    		    		    	    	String bool = this.querySqlToBoolean(sql);
    		    		    	    	if("true".equals(bool)){
    		    		        	    	logger.info("满足条件");
    		    		    	    	}else{
    		    		    	    		logger.info("不满足条件");
    		    		        	    	j++;
    		    		    	    	}
    		    		    		}
    		    		    	}
    		    		    	//判断如果有一个不满足条件 不录入日志表
    		    		    	if(j>0){
    		    		    		logger.info("不录入日志，有不满足的");
    		    		    	}else{
    		    		    		logger.info("录入日志");
    		    			    	if(type.contains("1")){
    		    						//发送邮件
    		    						List lsmail = this.queryPerson(mo.getId());
    							        List<String> supList = new ArrayList<String>();
    							        Iterator it = lsmail.iterator();   
    							        while(it.hasNext()) {       
    							        	Map userMap = (Map) it.next();       
    							        	supList.add(userMap.get("email").toString());
    							        } 
    							    	String[] str = new String[supList.size()];  //创建一个String型数组
    							    	supList.toArray(str); //将List数组转为String数组
    							    	//-----------------------发送邮件-----------------------
    							    	String title="邮件"+name+"";
    							    	String text="邮件内容"+msg+"";
    							    	//（接收者，邮件头，邮件行）
    							    	m.sendTextWithHtml(str,title,text);
    		    					} 
    		    					if(type.contains("2")){
    		    						//短信
    		    					} 
    		    					if(type.contains("3")){
    		    						//执行shell命令
    		    					    try
    		    		                {
    		    					    	Process ps = Runtime.getRuntime().exec(shell); 
    			    					    ps.waitFor(); 
    			    					
    			    					    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); 
    			    					    StringBuffer sb = new StringBuffer(); 
    			    					    String line; 
    			    					    while ((line = br.readLine()) != null) { 
    			    					      sb.append(line).append("\n"); 
    			    					    } 
    			    					    String result = sb.toString(); 
    			    					    logger.warn("====执行shell的返回值======="+result); 
    		    		                }
    		    		                catch (Exception e)
    		    		                { 
    		    		    				logger.warn("warn执行shell出错:"+e);
    		    		                }
    		    					}
    		    			    	String sql = "select count(*) from iyw_watch_item_trigger_log where trigger_id="+id+" and msg='"+msg+"' and is_handle='N'";
    		    			        int logi = queryLog(sql);
    		    			        if(logi<1){
    		    			    	//录入日志
    		    			    	Object[] param = new Object[] {id,new Date(),msg,"N"};
    		    			    	jdbcTemplate.update("insert into iyw_watch_item_trigger_log(trigger_id,trigger_time,msg,is_handle) values(?,?,?,?)",   
    		    			    			param);
    		    			        }
    			    		    	//修改是否后续处理为Y
    			    				Object[] params = new Object[] {id};
    			    		    	jdbcTemplate.update("update iyw_watch_item_trigger set is_conntinue='Y' where id=?",params);
    		    		    	}
    						}else{
    							
    							//获取触发器条目信息
    		    		    	List ls2 = this.queryForItemTriggerLine(id);
    		    		    	int j = 0;
    		    		    	if(ls2 != null){
    		    		    		//循环比对条目
    		    		    		for(int k = 0;k<ls2.size();k++){
    		    		    			//获取符号与对比值
    		    		    	    	Map map2 = (Map)ls2.get(k);
    		    		    	    	String oper = (String)map2.get("oper");
    		    		    	    	String value = (String)map2.get("value");
    		    		    	    	if("==".equals(oper)){
    		    		    	    		oper = "=";
    		    		    	    	}
    		    		    	    	//条目比对是否满足，返回true false
    		    		    	    	String sql = "select if("+"'"+leftValue+"'"+oper+"'"+value+"'"+",\"true\",\"false\")";
    		    		    	    	String bool = this.querySqlToBoolean(sql);
    		    		    	    	if("true".equals(bool)){
    		    		        	    	logger.info("满足条件");
    		    		    	    	}else{
    		    		    	    		logger.info("不满足条件");
    		    		        	    	j++;
    		    		    	    	}
    		    		    		}
    		    		    	}
    		    		    	//判断如果有一个不满足条件 修改日志表
    		    		    	if(j>0){
    		    		    		logger.info("修改日志表");

    			    		    	//修改日志为自动处理
    		    			    	Object[] param = new Object[] {"Y","系统自动处理",new Date(),id};
    		    			    	jdbcTemplate.update("update iyw_watch_item_trigger_log set is_handle = ?,handle_msg = ?,handle_uid = (select uid from iyw_base_admin where username = 'admin'),handle_date = ? where trigger_id = ? and is_handle = 'N'",   
    		    			    			param);
    			    		    	//修改是否后续处理为N,自动修改
    			    				Object[] params = new Object[] {id};
    			    		    	jdbcTemplate.update("update iyw_watch_item_trigger set is_conntinue='N' where id=?",params);
    		    		    	}else{
    		    		    		logger.info("不修改日志表");
    		    		    	}
    							
    							
    							
    							
    							
    						}
    	        		}
    	        	}
    			} catch (Exception e) {
    				logger.warn("warn:"+e);
    	        	Object[] param = new Object[] {mo.getId(),leftValue,"Y",e,sdf2.format(new Date()),new Date(),mo.getWatch_item_id()};
    		    	jdbcTemplate.update("insert into iyw_watch_item_data(item_id,value,is_error,error_msg,run_period_day,run_date,watch_item_id) values(?,?,?,?,?,?)",   
    		    			param);
    			}
            }
    	}
        
    }  
	//获取传过来的sql值
	public Object queryMySql(String sql){
		return jdbcTemplate.queryForObject(sql, Object.class);
	}
	//获取触发器信息
	public List queryForItemTrigger(Long id){
		return jdbcTemplate.queryForList("select * from iyw_watch_item_trigger where watch_item_id ="+id);
	}
	//获取触发器条目信息
	public List queryForItemTriggerLine(Long id){
		return jdbcTemplate.queryForList("select * from iyw_watch_item_trigger_line where item_trigger_id ="+id);
	}
	//判断条目比对成功与否
	public String querySqlToBoolean(String sql){
		return jdbcTemplate.queryForObject(sql, String.class);
	}
	
	//获取触发器条目信息
	public List queryPerson(Long id){
		return jdbcTemplate.queryForList("select email from iyw_device_person where device_id in(select device_id from iyw_device_zabbix_watch where id in (select device_zabbix_id from iyw_device_item_assign where item_id = "+id+"))");
	}
	//获取触发器条目信息
	public Integer queryLog(String sql){
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}
}
